package com.hllxd.hism.star.basic.service.schedule;
//
//import com.bj58.job.core.biz.model.ReturnT;
//import com.bj58.job.core.handler.IJobHandler;
//import com.bj58.job.core.handler.annotation.JobHandler;
//import com.bj58.job.core.log.WJobLogger;
//import com.bj58.zp.cdata.star.basic.service.collect.CollectYarn;
//import com.bj58.zp.cdata.star.basic.service.collect.OkHttpUtil;
//import com.bj58.zp.cdata.star.basic.service.dao.mapper.mis.TimeoutTaskMngMapper;
//import com.bj58.zp.cdata.star.basic.service.model.TimeoutTaskEntity;
//import com.bj58.zp.cdata.star.basic.service.model.rock.YarnApplicationEntity;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.time.Instant;
//import java.time.LocalDateTime;
//import java.time.ZoneOffset;
//import java.time.temporal.ChronoUnit;
//import java.util.*;

/**
 * 任务Handler示例（Bean模式）     *
 * * 开发步骤：
 * * 1、继承"IJobHandler"：“IJobHandler”；
 * * 2、注册到执行器工厂：添加“@JobHandler(value="自定义jobhandler名称")”注解，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * * 3、执行日志：需要通过 "WJobLogger.log" 打印执行日志;
 */
//@JobHandler(value = "timeoutTaskJobHandler")
//如果是spring方式初始化的 需要加上component注解
//@Component
//public class TimeoutTaskJobHandler extends IJobHandler {

//    @Autowired
//    private TimeoutTaskMngMapper timeoutTaskMngMapper;
//
//    public static final int TIMEOUT_HOURS = 6;
//    public static final Set<String> APP_TYPE_SET = new HashSet<>();
//
//    static {
//        APP_TYPE_SET.add("MAPREDUCE");
////        APP_TYPE_SET.add("SPARKCORE");
//    }
//
//    @Override
//    public ReturnT<String> execute(String param) throws Exception {
//        WJobLogger.log("W-JOB, start.timeoutTaskJobHandler");
//
//        LocalDateTime nowLDT = LocalDateTime.now();
//        ArrayList<TimeoutTaskEntity> toKillList = new ArrayList<>();
//        HashMap<String, String> paramMap = new HashMap<>();
//        List<TimeoutTaskEntity> taskEntities = timeoutTaskMngMapper.listTimeoutTask(paramMap);
//        Set<String> appSet = new HashSet<>();
//        for (TimeoutTaskEntity taskEntity : taskEntities) {
//            appSet.add(taskEntity.getAppId());
//            Integer optStatus = taskEntity.getOptStatus();
//            Long submitTime = taskEntity.getSubmitTime();
//            Long delayTime = taskEntity.getDelayTime();
//            LocalDateTime submitTimeLDT = Instant.ofEpochMilli(submitTime).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
//            long untilHour = submitTimeLDT.until(nowLDT, ChronoUnit.HOURS);
//
//            if (optStatus == 1) {
//                if (untilHour >= TIMEOUT_HOURS) {
//                    toKillList.add(taskEntity);
//                }
//            } else {
//                long untilSec = submitTimeLDT.until(nowLDT, ChronoUnit.SECONDS);
//                if (untilSec > TIMEOUT_HOURS * 3600 + delayTime) {
//                    toKillList.add(taskEntity);
//                }
//            }
//        }
//
//        Map<String, String> params = new HashMap<>();
//        params.put("queue", "");
//        List<YarnApplicationEntity> appList = CollectYarn.getAppList(params);
//        ArrayList<YarnApplicationEntity> toInsertList = new ArrayList<>();
//        for (YarnApplicationEntity yarnApplication : appList) {
//            Long startedTime = yarnApplication.getStartedTime();
//            String id = yarnApplication.getId();
//            String applicationType = yarnApplication.getApplicationType();
//            LocalDateTime startedTimeLDT = Instant.ofEpochMilli(startedTime).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
//            long until = startedTimeLDT.until(nowLDT, ChronoUnit.HOURS);
//            if (until >= TIMEOUT_HOURS && !appSet.contains(id) && APP_TYPE_SET.contains(applicationType)) {
//                toInsertList.add(yarnApplication);
//            }
//        }
//
//        WJobLogger.log("toKillList:" + toKillList.size());
//        for (TimeoutTaskEntity timeoutTaskEntity : toKillList) {
//            WJobLogger.log("start kill appId:" + timeoutTaskEntity.getAppId());
//            killYarnApplication(timeoutTaskEntity.getAppId());
//            timeoutTaskMngMapper.updateTimeoutTaskActionByAppId(timeoutTaskEntity.getAppId());
//        }
//
//        WJobLogger.log("toInsertList:" + toInsertList.size());
//        for (YarnApplicationEntity yarnApplication : toInsertList) {
//            TimeoutTaskEntity entity = new TimeoutTaskEntity();
//            entity.setAppId(yarnApplication.getId());
//            entity.setAppName(yarnApplication.getName());
//            entity.setAppType(yarnApplication.getApplicationType());
//            entity.setSubmitTime(yarnApplication.getStartedTime());
//            entity.setLaunchTime(yarnApplication.getLaunchTime());
//            entity.setUseTime(yarnApplication.getUseTime());
//            entity.setQueue(yarnApplication.getQueue());
//            entity.setUser(yarnApplication.getUser());
//            entity.setOptStatus(1);
//            int i = timeoutTaskMngMapper.insert(entity);
//        }
//        WJobLogger.log("W-JOB, end.timeoutTaskJobHandler");
//        return SUCCESS;
//    }
//
//    private static final String KILL_API = "/ws/v1/cluster/apps/%s/state";
//
//    public Boolean killYarnApplication(String appId) {
//        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance();
//        String api = String.format(KILL_API, appId);
//        HashMap<String, String> param = new HashMap<>();
//        param.put("state", "KILLED");
//        try {
//            String request = CollectYarn.YARN_URL + api;
//            String res = okHttpUtil.putDataString(request, param);
//            WJobLogger.log("执行killYarnApplication url：" + request + ",param:" + param + ",result:" + res);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return true;
//    }
//}
